import React, { useRef, useEffect } from 'react';

export default () => {
  const ref = useRef(null);
  const storePointPosition = useRef(null);
  let ctx = null;

  // orgin
  const drawAxis = (config) => {
    ctx.save();
    const { origin, xAxis, yAxis } = config;
    const xAxisHeight = 5;
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'orange';
    ctx.beginPath();
    ctx.moveTo(origin.x, origin.y);
    ctx.lineTo(origin.x + xAxis.length, origin.y); // x 轴
    for (let i = 0; i < xAxis.length / xAxis.gap; i++) {
      const { gap } = xAxis;
      ctx.moveTo(origin.x + gap * i, origin.y - xAxisHeight);
      ctx.lineTo(origin.x + gap * i, origin.y)
    }

    for (let i = 0; i < yAxis.length / yAxis.gap; i++) {
      const { gap } = xAxis;
      ctx.moveTo(origin.x + xAxisHeight, origin.y - gap * i);
      ctx.lineTo(origin.x, origin.y - gap * i)
    }


    ctx.moveTo(origin.x, origin.y);
    ctx.lineTo(origin.x, origin.y - yAxis.length); // y 轴

    // x箭头
    ctx.moveTo(origin.x + xAxis.length, origin.y);
    ctx.lineTo(origin.x + xAxis.length - 6, origin.y - 4);
    ctx.moveTo(origin.x + xAxis.length, origin.y);
    ctx.lineTo(origin.x + xAxis.length - 6, origin.y + 4);

    // y箭头
    ctx.moveTo(origin.x, origin.y - yAxis.length);
    ctx.lineTo(origin.x + 6, origin.y - yAxis.length + 4);
    ctx.moveTo(origin.x, origin.y - yAxis.length);
    ctx.lineTo(origin.x - 6, origin.y - yAxis.length + 4);

    ctx.stroke();
    ctx.closePath();
    ctx.restore(); // 在画坐标轴的时候不会影响画布中其他位置
  }

  const addEvent = () => {
    ref.current.addEventListener('click', e => {
      const clickPosition = {
        x: e.clientX,
        y: e.clientY
      }
      const { left, top } = ref.current.getBoundingClientRect();
      const canvasOffset = {
        x: left,
        y: top
      }
      drawPoint(clickPosition.x - canvasOffset.x, clickPosition.y - canvasOffset.y, 5);
    });

    ref.current.addEventListener('mousemove', e => {
      const clickPosition = {
        x: e.clientX,
        y: e.clientY
      }
      const { left, top } = ref.current.getBoundingClientRect();
      const canvasOffset = {
        x: left,
        y: top
      }
      drawPoint(clickPosition.x - canvasOffset.x, clickPosition.y - canvasOffset.y, 5);
    });
  }

  const drawPoint = (cx, cy, r) => {
    ctx.save();

    ctx.lineWidth = 1;
    ctx.moveTo(cx, cy);
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.fillStyle = '#fff';
    ctx.fill();
    ctx.strokeStyle = 'blue';
    ctx.stroke();
    ctx.closePath()

    ctx.restore();
  }
  useEffect(() => {
    ctx = ref.current?.getContext('2d');
    drawAxis({
      origin: {
        x: 1,
        y: 220
      },
      xAxis: {
        length: 400,
        gap: 10
      },
      yAxis: {
        length: 200,
        gap: 10
      }
    });
    addEvent();

  }, [])
  return <canvas ref={ref} width={500} height={500}></canvas>
};


